import os
from collections import Counter

def read_paper(file_path: str) -> Counter:
    """读取英文文本文件并统计单词出现次数"""
    if not os.path.isfile(file_path):
        raise FileNotFoundError(f"文件不存在: {file_path}")
    
    word_counter = Counter()
    try:
        with open(file_path, 'r', encoding='utf-8') as fin:
            for line in fin:
                # 移除行末空白字符并分割单词
                words = line.strip().split()
                # 规范化每个单词并更新计数器
                for word in words:
                    # 移除标点符号并转为小写
                    clean_word = word.strip('.,?!:;"\'').lower()
                    if clean_word:  # 过滤空字符串
                        word_counter[clean_word] += 1
    except Exception as e:
        raise RuntimeError(f"读取文件时发生错误: {e}")
    
    if not word_counter:
        raise ValueError("文件中未找到有效单词")
    
    return word_counter

def analyze_words(word_counter: Counter, top_n: int = 10) -> None:
    """分析并打印单词统计信息"""
    total_words = sum(word_counter.values())
    unique_words = len(word_counter)
    
    print(f"=== 文本分析结果 ===")
    print(f"总单词数: {total_words:,}")
    print(f"唯一单词数: {unique_words:,}")
    print(f"词汇丰富度: {unique_words / total_words:.2%}")
    
    print("\n--- 出现频率最高的10个单词 ---")
    for rank, (word, count) in enumerate(word_counter.most_common(top_n), 1):
        print(f"{rank:2d}. {word:<15} {count:5d} 次 ({count/total_words:.2%})")

def main() -> None:
    """主程序入口"""
    try:
        # 构建文件路径
        file_path = os.path.join(os.getcwd(), "01-exercise/01-20/English_paper.txt")
        
        # 读取并分析文本
        word_counter = read_paper(file_path)
        analyze_words(word_counter)
        
    except FileNotFoundError as e:
        print(f"错误: {e}")
        print("请检查文件路径是否正确")
    except ValueError as e:
        print(f"错误: {e}")
    except RuntimeError as e:
        print(f"运行时错误: {e}")
    except Exception as e:
        print(f"发生未知错误: {e}")

if __name__ == "__main__":
    main()